﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BadHabit.Factory.Tail {

    public class PreCommitHook : BaseHook  {

        /// <summary>
        /// Main program.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args) {

            // gets the repository and the transaction
            if (args.Length > 1) {
                Repository = args[0];
                Transaction = args[1];
            } else {
                Console.WriteLine("Use: pre-commit Repository Transaction");
                return;
            }

            string user = GetMadeByUser();
            

            string comment = GetComment();
            
            // if is not tailed task, get out
            if (!IsTailed(comment))
                return;

            // get the task Id
            int taskId = GetTaskId(comment);

            // get resolve task number
            bool resolveTaskNumber = false;
            resolveTaskNumber = GetResolveTaskNumber();
            
            // no task Id, return error
            if (taskId < 0 && resolveTaskNumber==false) {
                System.Console.Error.WriteLine("Please, provide a task number in order to commit your job.");
                Environment.ExitCode = 1;
                return;
            }

            // sets the server    
            try {
                SetFactoryServer();
            } catch (Exception) {
                System.Console.Error.WriteLine("Could not find the Scrum Factory Server.");
                Environment.ExitCode = 1;
                return;
            }

            string repositoryUrl;
            repositoryUrl = GetRepositoryUrl();

            // if no task was informed try to guessed it            
            if (taskId < 0) {
                try {
                    
                    

                    string taskUId = service.RetriveTeamMemberWorkingTaskUId(user);
                    if (taskUId == null || taskUId.Trim().Equals(Guid.Empty.ToString())) {
                        System.Console.Error.WriteLine("You (" +  user + ") are not working at any task now. Can not commit.");
                        Environment.ExitCode = 1;
                        return;
                    }
                } catch (Exception ex) {                    
                    System.Console.Error.WriteLine("Scrum Factory: Error verifing current user task.\n\n" + ex.Message);
                    System.Console.Error.WriteLine(service.FactorySOAPHeaderValue.FactoryClientMinVersion);
                    Environment.ExitCode = 1;
                    return;
                }
            }

                        
            
        }
     
    }
}
